<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" append-to-body>
    <el-form
      v-loading="dialogLoading"
      :model="dialogFormData"
      label-width="80px"
      ref="dialogFormRef"
    >
      <el-form-item label="菜谱">
        <el-table :data="dialogFormData.recipeList" class="-mt-10px">
          <el-table-column label="菜谱" min-width="180" label-class-name="!text-center">
            <template #default="{ $index, row }">
              <div v-show="row.mealId">
                <!-- 已有菜谱：显示菜谱名称 + 更换按钮 -->
                <div class="flex items-center">
                  <span class="flex-1">{{ row.recipeName }}</span>
                  <!-- 更换菜谱弹窗 -->
                  <el-popover
                    :ref="(e) => (popoverRefMap[$index] = e)"
                    placement="top"
                    :width="300"
                    trigger="click"
                    :hide-after="0"
                  >
                    <template #reference>
                      <el-button link type="primary">更换</el-button>
                    </template>
                    <div class="mb-10px">选择新菜谱：</div>
                    <el-cascader
                      popper-class="foods-cascader"
                      v-model="row.newRecipeValue"
                      :options="recipeOptions"
                      :props="cascaderProps"
                      clearable
                      filterable
                      placeholder="请选择菜谱"
                      class="w-full mb-10px"
                      @change="(val) => handleRecipeChange(val, row)"
                      :teleported="false"
                    />
                    <div class="text-right">
                      <el-button size="small" @click="popoverRefMap?.[$index]?.hide?.()"
                        >取消</el-button
                      >
                      <el-button
                        size="small"
                        type="primary"
                        @click="updateRecipe(row, $index)"
                        :disabled="!row.newRecipeValue"
                      >
                        确定
                      </el-button>
                    </div>
                  </el-popover>
                </div>
              </div>
              <div v-show="!row.mealId">
                <!-- 新增菜谱：显示级联选择器 -->
                <el-cascader
                  popper-class="foods-cascader"
                  v-model="row.recipeValue"
                  :options="recipeOptions"
                  :props="cascaderProps"
                  clearable
                  filterable
                  placeholder="请选择菜谱"
                  class="w-full"
                  @change="(val) => handleRecipeSelect(val, row)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="食材总量(克)"
            prop="totalUsages"
            min-width="120"
            label-class-name="!text-center"
          >
            <!-- <template #default="{ row }">
              <div v-if="row.usagesList && row.usagesList.length > 0">
                <div v-for="(usage, uIndex) in row.usagesList" :key="uIndex">
                  {{ usage.foodName }}: {{ usage.usage }}
                </div>
              </div>
              <div v-else>0</div>
            </template> -->
          </el-table-column>
          <el-table-column align="center" label="操作" width="60" label-class-name="!text-center">
            <template #default="{ $index }">
              <el-button @click="handleDeleteRecipe($index)" link>—</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex justify-end mt-3 w-full">
          <el-button @click="handleAddRecipe" round>+ 添加菜谱</el-button>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { RecipesTypeApi } from '@/api/school/recipe/recipeType'
import { RecipeMenusDailyApi } from '@/api/school/recipe/menusDaily'
import { defaultProps } from '@/utils/tree'

defineOptions({ name: 'RecipeMenusForm' })

const message = useMessage()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogLoading = ref(false)
const dialogFormRef = ref()
const popoverRefMap = ref({})
// 表单数据
const dialogFormData = reactive({
  menuId: undefined,
  menuDate: undefined,
  mealType: '',
  totalUsages: 0,
  recipeList: [] as any[]
})

// 菜谱级联选项
const recipeOptions = ref<any[]>([])

// 级联属性
const cascaderProps: any = reactive({
  ...defaultProps,
  multiple: false
  // lazy: true,
  // emitPath: false // 不返回路径数组，只返回叶子节点值
  // lazyLoad: async (node, resolve) => {
  //   const { level, data } = node

  //   if (level === 0) {
  //     // 加载菜谱分类
  //     try {
  //       const res = await RecipesTypeApi.getRecipesTypeSimpleList()
  //       const options = res.map((item: any) => ({
  //         id: item.typeId,
  //         name: item.typeName,
  //         leaf: false
  //       }))
  //       resolve(options)
  //     } catch (err) {
  //       resolve([])
  //     }
  //   } else if (level === 1) {
  //     // 加载菜谱
  //     try {
  //       const res = await RecipesApi.getRecipesList(data.id)
  //       const options = res.map((item: any) => ({
  //         id: item.recipeId, // 改回使用item.recipeId作为菜谱ID
  //         name: item.recipeName,
  //         leaf: true,
  //         usagesList: item.usagesList || []
  //       }))
  //       resolve(options)
  //     } catch (err) {
  //       resolve([])
  //     }
  //   } else {
  //     resolve([])
  //   }
  // }
})
const getRecipesListTree = async () => {
  try {
    const res = await RecipesTypeApi.getRecipeFoodTree()
    recipeOptions.value = res || []
  } catch (err) {
    console.error(err)
  }
}
// 添加菜谱
const handleAddRecipe = () => {
  dialogFormData.recipeList.push({
    recipeValue: '', // 字符串形式，不是数组
    recipeName: '',
    totalUsages: 0,
    usagesList: [],
    mealId: undefined
  })
}

// 删除菜谱
const handleDeleteRecipe = async (index: number) => {
  const recipe = dialogFormData.recipeList[index]
  // 如果有mealId，说明是已存在的菜谱，需要调用删除接口
  if (recipe.mealId) {
    try {
      await RecipeMenusDailyApi.deleteRecipeMenusDaily(recipe.mealId)
      message.success('删除成功')

      // 从列表中移除
      dialogFormData.recipeList.splice(index, 1)

      // 触发保存事件，并传递删除信息
      emit('save', {
        type: 'delete',
        mealId: recipe.mealId,
        index: index
      })
    } catch (err) {
      message.error('删除失败')
      return
    }
  } else {
    // 直接从列表中移除（未保存到数据库的）
    dialogFormData.recipeList.splice(index, 1)

    // 触发保存事件
    emit('save', {
      type: 'delete',
      index: index
    })
  }
}

// 菜谱选择（新增菜谱时）
const handleRecipeSelect = async (value: any, row: any) => {
  // value现在是字符串
  if (value) {
    await createRecipe(row, value)
  }
}
// 创建菜谱
const createRecipe = async (row: any, recipeId: string) => {
  dialogLoading.value = true
  try {
    const data: any = {
      menuId: dialogFormData.menuId,
      mealType: dialogFormData.mealType,
      recipeId: recipeId,
      menuDate: dialogFormData.menuDate // 使用从父组件传递的menuDate
    }

    const res = await RecipeMenusDailyApi.createRecipeMenusDaily(data)

    // 更新行数据
    row.mealId = res.id
    row.recipeValue = recipeId // 字符串形式，不是数组

    message.success('创建成功')

    // 触发保存事件
    emit('save', {
      type: 'create',
      mealId: res.id,
      recipeId: recipeId
    })
  } catch (err) {
    message.error('创建失败')
    // 清空选择
    row.recipeValue = ''
    row.recipeName = ''
    row.usagesList = []
  } finally {
    dialogLoading.value = false
  }
}

// 更新菜谱（更换菜谱时）
const updateRecipe = async (row: any, index: number) => {
  if (!row.newRecipeValue) {
    message.warning('请选择菜谱')
    return
  }

  dialogLoading.value = true
  try {
    const recipeId = row.newRecipeValue // 字符串形式，不是数组

    // 获取新的菜谱信息
    const formFields = dialogFormRef.value?.form?.fields || []
    let newRecipeName = ''
    let newUsagesList: any[] = []

    // 查找对应的级联组件
    for (const field of formFields) {
      if (field.componentInstance && field.componentInstance.$.vnode.props) {
        const props = field.componentInstance.$.vnode.props
        if (props.modelValue === row.newRecipeValue) {
          // 找到对应的级联组件
          if (field.panel && field.panel.nodes) {
            // 获取当前选中的节点
            const nodes = field.panel.nodes
            const selectedNode = nodes[nodes.length - 1] // 最后一个节点是选中的菜谱

            if (selectedNode && selectedNode.data) {
              newRecipeName = selectedNode.data.name
              newUsagesList = selectedNode.data.usagesList || []
            }
          }
          break
        }
      }
    }

    const data: any = {
      id: row.mealId,
      menuId: dialogFormData.menuId,
      mealType: dialogFormData.mealType,
      recipeId: recipeId,
      menuDate: dialogFormData.menuDate // 使用从父组件传递的menuDate
    }

    await RecipeMenusDailyApi.updateRecipeMenusDaily(data)

    // 更新行数据
    row.recipeName = newRecipeName
    row.usagesList = newUsagesList
    row.newRecipeValue = '' // 字符串形式，不是数组
    popoverRefMap.value?.[index]?.hide?.()

    message.success('更新成功')

    // 触发保存事件
    emit('save', {
      type: 'update',
      recipeId: recipeId,
      recipeName: newRecipeName,
      usagesList: newUsagesList
    })
  } catch (err) {
    message.error('更新失败')
  } finally {
    dialogLoading.value = false
  }
}

// 处理级联组件值变化（用于更换菜谱）
const handleRecipeChange = (value: any, row: any) => {
  if (value) {
    // 获取选中的菜谱信息
    const formFields = dialogFormRef.value?.form?.fields || []

    // 查找对应的级联组件
    for (const field of formFields) {
      if (field.componentInstance && field.componentInstance.$.vnode.props) {
        const props = field.componentInstance.$.vnode.props
        if (props.modelValue === value) {
          // 找到对应的级联组件
          if (field.panel && field.panel.nodes) {
            // 获取当前选中的节点
            const nodes = field.panel.nodes
            const selectedNode = nodes[nodes.length - 1] // 最后一个节点是选中的菜谱

            if (selectedNode && selectedNode.data) {
              // 更新菜谱名称和食材列表
              row.recipeName = selectedNode.data.name
              row.usagesList = selectedNode.data.usagesList || []
            }
          }
          break
        }
      }
    }
  } else {
    row.recipeName = ''
    row.usagesList = []
  }
}

// 打开弹窗
const open = (data: any) => {
  dialogVisible.value = true
  dialogTitle.value = '编辑菜谱'

  // 初始化表单数据
  dialogFormData.menuId = data.menuId
  dialogFormData.mealType = data.mealType
  dialogFormData.menuDate = data.menuDate // 保存从父组件传入的 menuDate
  dialogFormData.recipeList = []
  dialogFormData.totalUsages = 0

  // 填充已有菜谱数据
  if (data.recipeList && data.recipeList.length > 0) {
    data.recipeList.forEach((recipe: any) => {
      dialogFormData.recipeList.push({
        recipeValue: recipe.recipeId,
        recipeName: recipe.recipeName || '',
        usagesList: recipe.usagesList || [],
        totalUsages: recipe.totalUsages || 0,
        mealId: recipe.mealId,
        newRecipeValue: '',
        showPopover: false
      })
    })
  }

  // 如果没有菜谱，添加一个空的
  if (dialogFormData.recipeList.length === 0) {
    handleAddRecipe()
  }
}

// 定义事件
const emit = defineEmits<{
  (e: 'save', result?: any): void
}>()
onMounted(() => {
  // 获取菜谱分类列表
  getRecipesListTree()
})
// 暴露方法
defineExpose({ open })
</script>
<style lang="scss">
@import url('../style.scss');
</style>
